package net.cloudcodex.client.character.view.panel;

import java.util.Date;

import net.cloudcodex.client.util.ClientUtils;
import net.cloudcodex.client.widgets.CharacterAvatar;
import net.cloudcodex.shared.dto.campaign.character.CharacterNoteDTO;

import com.google.gwt.event.dom.client.HasKeyDownHandlers;
import com.google.gwt.event.dom.client.HasKeyUpHandlers;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.TextArea;

public class NotesPanel extends DockPanel implements HasKeyDownHandlers,
		HasKeyUpHandlers {
	private TextArea notesTextArea = new TextArea();
	private final CharacterAvatar characterAvatar = new CharacterAvatar();
	private Long author;
	private String content = "";
	private Long characterID ;

	public NotesPanel() {
	}

	public void initComponents() {

		if (characterAvatar != null) {
			this.add(characterAvatar, DockPanel.WEST);
		}
		notesTextArea.setText(content);
		notesTextArea.setTitle("author : " + getAuthor());
		this.add(notesTextArea, DockPanel.CENTER);
	}

	private String getAuthor() {
		String result = "" + author;
		if (author == null) {
			result = "GM";
		}
		return result;
	}

	public TextArea getNotesTextArea() {
		return notesTextArea;
	}

	public void addCharacterNote(String content) {
		this.content = content;

	}

	public void addCharacterAvatar(Long id, String icon, String name) {
		this.characterAvatar.initComponent(icon, name, true);
		this.characterAvatar.resize("30", "30");
		this.characterAvatar.setId(id);
	}

	public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) {
		return notesTextArea.addKeyUpHandler(handler);
	}

	public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) {
		return notesTextArea.addKeyDownHandler(handler);
	}

	public void addCharacterNoteID(Long characterID) {
		this.characterID = characterID;

	}

	public CharacterNoteDTO getChangedNotes() {
		String newNotes = notesTextArea.getText();
		if ((ClientUtils.getChangedText(newNotes, content)) != null) {
			CharacterNoteDTO noteDTO = new CharacterNoteDTO();
			noteDTO.setAuthor(author);
			noteDTO.setContent(newNotes);
			noteDTO.setTimestamp(new Date());
			return noteDTO ;
		}
		return null;
	}

	public void refreshNote(String content) {
		this.content = content ;
		notesTextArea.setText(content);
	}

	public Long getNoteAuthor() {
		return author;
	}

	public void addAuthor(Long authorID) {
		this.author = authorID;
	}

}
